package xyz.lwm.lazycat.transaction.policy;

import xyz.lwm.lazycat.transaction.execute.TranDefinition;
import xyz.lwm.lazycat.transaction.execute.Transaction;
import xyz.lwm.lazycat.transaction.execute.TransactionManager;

/**
 * 若存在当前事务，则加入当前事务，若不存在当前事务，则创建新的事务
 *
 * @author lwm
 * @see xyz.lwm.lazycat.transaction.execute.Propagation#REQUIRED
 */
class RequiredPolicy extends AbstractPolicy {

    public RequiredPolicy(TranDefinition tranDefinition) {
        super(tranDefinition);
    }

    @Override
    public <T> T execute(CheckedSupplier<T> supplier) throws Throwable {
        Transaction tran = TransactionManager.current();
        if (tran.isOpen()) {
            return supplier.get();
        }
        return new RequiresNewPolicy(tranDefinition).execute(supplier);
    }

}
